package com.cowcow.house.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@Configuration
@EnableWebSecurity //@EnableWebSecurity是开启SpringSecurity的默认行为
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .withUser("lucy")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .roles("");
//
//    }

    /**
     * 必须指定加密方式，上下加密方式要一致
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        //必须调用父类的方法，否则就不需要认证即可访问
//        super.configure(http);
//        //允许iframe嵌套显示
//        //http.headers().frameOptions().disable();
//        //允许iframe显示
//        http.headers().frameOptions().sameOrigin();
//    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许iframe嵌套显示
        http.headers().frameOptions().disable();
        //登录设置
        http
                .authorizeRequests()
                .antMatchers("/static/**", "/loginPage").permitAll()  //允许匿名用户访问的路径
                .anyRequest().authenticated();    // 其它页面全部需要验证

        //自定义登录页面
        http.formLogin()
                .loginPage("/loginPage")
                // .usernameParameter("username") //默认值就是username
                // .passwordParameter("password") // 默认值就是password
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/");

        //自定义注销功能
        http.logout().logoutUrl("/logout")
                .invalidateHttpSession(true)
                .logoutSuccessUrl("/loginPage");

        //取消CSRF
        http.csrf().disable();//注销功能需要禁用csrf


        http.exceptionHandling().accessDeniedHandler(new CustomAccessDeineHandler());

    }
}
